<!-- 系统消息 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发送时间" style="width: 428px;">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange" :default-time="[new Date(2000, 1, 1, 0, 0, 0),
        new Date(2000, 2, 1, 23, 59, 59),]" range-separator="-" start-placeholder="开始时间"
          end-placeholder="结束时间"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['comlbs:messSend:add']">下发</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table highlight-current-row v-loading="loading" :data="messSendList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column :label="v.name" align="left" :prop="v.prop" v-for="v in tableItems" :width="v.width"
        show-overflow-tooltip>
        <template #default="scope">
          <dict-tag v-if="v.type == 'dict'" :options="sel_option[v.option]" :value="scope.row[v.prop]" />
          <span v-else>{{ scope.row[v.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left">
        <template #default="scope">
          <el-button link type="primary" @click="showDetail(scope.row)"
            v-hasPermi="['comlbs:messSend:detail']">详情</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['comlbs:messSend:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改发送消息对话框 -->
    <el-dialog :title="title" v-model="open" width="1100px" append-to-body destroy-on-close>
      <el-form class="form" :model="form" :rules="rules" ref="messSendRef" label-width="100px">
        <div class="body_form">
          <el-form-item label="标题：" prop="title" style="margin-bottom: 32px;">
            <el-input type="textarea" :rows="3" :maxlength="20" placeholder="请输入标题" v-model="form.title"></el-input>
          </el-form-item>
          <el-form-item label="消息内容：" prop="content" style="margin-bottom: 32px;">
            <el-input type="textarea" :rows="15" placeholder="请输入内容" v-model="form.content">
            </el-input>
          </el-form-item>
          <el-form-item label="定时发送：">
            <el-date-picker v-model="form.sendTime" type="datetime" placeholder="选择日期时间" style="width: 200px" />
          </el-form-item>
        </div>
        <div class="body_Tree">
          <div class="ex-treeBox-title">请选择接收人</div>
          <div class="ex-treeBox-body">
            <el-tabs v-model="activeIndex" @tab-change="handleSelect" style="height:40px">
              <el-tab-pane label="角色选择" name="1"></el-tab-pane>
              <el-tab-pane label="组织架构" name="2"></el-tab-pane>
            </el-tabs>
            <div class="botm-body" v-show="activeIndex == 1">
              <el-input class="filter-input" placeholder="请输入关键字" v-model="searchName" prefix-icon="Search"
                style="margin-top: 10px;" clearable>
              </el-input>
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
                @change="handleCheckAllChange">全选</el-checkbox>
              <div class="jiaosenAttr">
                <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
                  <el-checkbox v-for="tiem in filterRoleArr" :label="tiem.roleId" :key="tiem.roleId">
                    {{ tiem.roleName }}</el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
            <currentTree class="botm-body" :filterShow="true" :treeList="treeList" ref="myTree" v-show="activeIndex == 2">
            </currentTree>
          </div>
        </div>
        <div class="body_role">
          <div class="ex-treeBox-title">已选择接收人</div>
          <ul class="ex-treeBox-body">
            <li class="green-bar overflow-text" v-for="item in selectedPeople" :key="item.id"
              style="width:44%;display:inline-block;margin:5px;margin-top:0">
              {{ item.label }}
              <el-icon title="移除" class="delete-bar" @click="handleDeleteNowSelectList(item.id)">
                <Close />
              </el-icon>
            </li>
          </ul>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog title="详情" v-model="detailOpen" width="800px" append-to-body>
      <div class="body" style="height: 450px;overflow: auto;">
        <el-form :model="InfoDataX" label-width="100px" class="InfoDataXForm">
          <el-form-item label="标题：">
            <span>{{ InfoDataX.title }}</span>
          </el-form-item>
          <el-form-item label="创建人：">
            <span>{{ InfoDataX.createUserName }}</span>
          </el-form-item>
          <el-form-item label="创建时间：">
            <span>{{ InfoDataX.createTime }}</span>
          </el-form-item>
          <el-form-item label="发送时间：">
            <span>{{ InfoDataX.sendTime }}</span>
          </el-form-item>
          <el-form-item label="内容：" class="textarea" style="width:100%">
            <div sty>{{ InfoDataX.content }}</div>
          </el-form-item>
        </el-form>
        <el-table :data="tableDataX">
          <el-table-column :label="v.name" align="left" :prop="v.prop" v-for="v in tableItemsX" :width="v.width"
            show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row[v.prop] }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="MessSend">
import { listMessSend, getMessSend, delMessSend, addMessSend, updateMessSend, getRoleManageListAll, getCompanyUsersTree } from "@/api/comlbs/messSend";
import dayjs from "dayjs";
import currentTree from "./currentTree.vue"

const { proxy } = getCurrentInstance();

const messSendList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const activeIndex = ref("1");

const checkAll = ref(false)
const checkedCities = ref([])
const myTree = ref(null);
const isIndeterminate = ref(false)
const searchName = ref("");
const roleArr = ref([]);// 角色 
const filterRoleArr = ref([]);// 筛选角色 
const treeList = ref([]);// 用户树 
const nodeLists = ref([]);// 树的一维数组
const selectedPeople = ref([]);// 已选择的人员 
// 详情
const detailOpen = ref(false)
const InfoDataX = ref({})
const tableDataX = ref([])
const tableItemsX = ref([
  { name: "接收人", prop: "receiveUserName" },
  { name: "接收时间", prop: "receiveTime" },
  { name: "查看时间", prop: "readTime" }
])

const dateRange = ref([dayjs(new Date()).format("YYYY-MM-DD 00:00:00"), dayjs(new Date()).format("YYYY-MM-DD 23:59:59")]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 15,
  },
  rules: {
    title: [
      { required: true, message: "请输入标题", trigger: "blur" },
    ],
    content: [
      { required: true, message: "请输入消息内容", trigger: "blur" },
    ]
  }
});
const tableItems = ref([
  { name: "标题", prop: "title" },
  { name: "内容", prop: "content" },
  { name: "接收人", prop: "receiveUserNames" },
  { name: "创建时间", prop: "createTime" },
  { name: "发送时间", prop: "sendTime" },
  { name: "创建人", prop: "createUserName" },
])
const { queryParams, form, rules } = toRefs(data);

onMounted(() => {
  getRoleManageListAll().then(response => {
    if (response.code != 200) return
    roleArr.value = response.data
    filterRoleArr.value = response.data
  })
  getCompanyUsersTree().then(response => {
    if (response.code != 200) return
    treeList.value = response.data
    createTree(treeList.value)
  })
})

/** 查询发送消息列表 */
function getList() {
  loading.value = true;
  queryParams.value.startTime = dateRange.value ? dateRange.value[0] : ''
  queryParams.value.endTime = dateRange.value ? dateRange.value[1] : ''
  listMessSend(queryParams.value).then(response => {
    messSendList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function handleSelect(index) {
  activeIndex.value = index;
}
function handleDeleteNowSelectList(id) {
  for (let i = 0; i < selectedPeople.value.length; i++) {
    if (selectedPeople.value[i].id === id) {
      selectedPeople.value.splice(i, 1);
      form.value.receiveUserIds.splice(i, 1);
      break;
    }
  }
  myTree.value.$refs.myTree.setCheckedKeys(form.value.receiveUserIds);
  if (selectedPeople.value.length === 0) {
    myTree.value.$refs.myTree.setCheckedKeys([]);
    handleCheckAllChange();
  }
}
//全选
function handleCheckAllChange(val) {
  checkedCities.value = val ? filterRoleArr.value.map(x => x.roleId) : [];
  isIndeterminate.value = false;
  setTree(checkedCities.value)
}
// 单选
function handleCheckedCitiesChange(ids) {
  let checkedCount = ids.length;
  checkAll.value = checkedCount === roleArr.value.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < roleArr.value.length;
  setTree(ids)
}
// 设置树勾选状态
function setTree(ids) {
  let InfoData = form.value;
  InfoData.receiveUserIds = []
  selectedPeople.value = []

  ids.forEach(val => {
    nodeLists.value.forEach(v => {
      if (v.roleid && v.roleid.indexOf(val) > -1 && !InfoData.receiveUserIds.includes(v.id)) {
        InfoData.receiveUserIds.push(v.id)
        selectedPeople.value.push({ label: v.name, id: v.id })
      }
    });
  })
  myTree.value.$refs.myTree.setCheckedKeys(InfoData.receiveUserIds)
}
// 遍历树，获取人员节点
function createTree(tree) {
  if (tree.length > 0) {
    for (let i = 0; i < tree.length; i++) {
      tree[i].disabled = true
      if (tree[i].roleIds) {
        tree[i].disabled = false
        nodeLists.value.push({ name: tree[i].label, roleid: tree[i].roleIds, id: tree[i].id, parentId: tree[i].parentId })
      } else if (tree[i].children && tree[i].children.length > 0) {
        tree[i].disabled = false
        createTree(tree[i].children)
      }
    }
  }
}
//树 勾选事件
function handleCheck(data, e) {
  form.value.receiveUserIds = []
  selectedPeople.value = []
  for (let i = 0; i < e.checkedNodes.length; i++) {
    if (e.checkedNodes[i].roleIds) {  //是人员
      form.value.receiveUserIds.push(e.checkedNodes[i].id);
      selectedPeople.value.push(e.checkedNodes[i]);
    }
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    content: null,
    receiveUserId: null,
    sendTime: null,
    isSend: null,
    messType: null,
    isRead: null,
    msgParm: null,
    userIdCreate: null,
    createTime: null,
    isDel: null
  };
  proxy.resetForm("messSendRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  queryParams.value.startTime = dateRange.value ? dateRange.value[0] : ''
  queryParams.value.endTime = dateRange.value ? dateRange.value[1] : ''
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  dateRange.value = [dayjs(new Date()).format("YYYY-MM-DD 00:00:00"), dayjs(new Date()).format("YYYY-MM-DD 23:59:59")];
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "下发";

  // 重置参数
  activeIndex.value = '1';
  searchName.value = "";
  checkAll.value = false;
  isIndeterminate.value = false;
  checkedCities.value = [];
  selectedPeople.value = [];
}

/** 提交按钮 */
function submitForm() {
  let userids = []
  form.value.receiveUserIds.forEach(v => {
    userids.push(v.split('_')[1])
  })
  let _data = {
    receiveUserId: userids.join(','),
    title: form.value.title,
    messType: 0,
    content: form.value.content,
    sendTime: form.value.sendTime ? dayjs(form.value.sendTime).format("YYYY-MM-DD HH:mm:ss") : null,
  }
  proxy.$refs["messSendRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateMessSend(_data).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMessSend(_data).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  let length = row.id ? 1 : _ids.length
  proxy.$modal.confirm('是否确认删除这' + length + '项数据？').then(function () {
    return delMessSend(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('comlbs/messSend/export', {
    ...queryParams.value
  }, `messSend_${new Date().getTime()}.xlsx`)
}
function showDetail(row) {
  detailOpen.value = true
  getMessSend(row.id).then(response => {
    if (response.code == 200) {
      InfoDataX.value = response.data;
      tableDataX.value = response.data.messReceiveList;
    }
  });
}
getList();

defineExpose({
  handleCheck
});
watch(searchName, () => {
  filterRoleArr.value = roleArr.value.filter(v => {
    if (searchName.value) {
      return v.roleName.includes(searchName.value)
    }
    return true
  })
})
</script>
<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  height: 100%;

  .body_form {
    flex: 1;
    margin-right: 20px;
  }

  .body_Tree {
    width: 300px;
    height: 500px;
    border: 1px solid #dadada;
    border-right: 0;

    .botm-body {
      height: calc(100% - 105px);
      width: 100%;

      .jiaosenAttr {
        height: calc(100% - 40px);
        overflow-y: auto;
        overflow-x: hidden;
      }
    }

    .el-menu--horizontal>.el-menu-item {
      height: 4rem;
      line-height: 4rem;
    }
  }

  .body_role {
    width: 380px;
    height: 500px;
    border: 1px solid #dadada;

    .green-bar {
      height: 30px;
      background-color: #f4f6fe;
      border-radius: 4px;
      text-align: center;
      box-sizing: border-box;
      padding: 5px 15px;
      position: relative;
      border: 1px solid var(--el-color-primary-light-6);

      .delete-bar {
        position: absolute;
        right: 4px;
        top: 8px;
        cursor: pointer;
      }
    }
  }

  .ex-treeBox-title {
    background-color: #f4f6fe;
    font-size: 16px;
    font-weight: 600;
    color: #223355;
    line-height: 50px;
    border-bottom: 1px solid #dadada;
    padding-left: 16px;
    box-sizing: border-box;
  }

  .ex-treeBox-body {
    padding: 12px;
    height: calc(100% - 50px);
    overflow-y: auto;
  }
}

:v-deep(.el-form-item__content) {
  align-items: normal;
}

.InfoDataXForm {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;

  .el-form-item {
    width: 50%;
  }
}
</style>